from django.shortcuts import render,redirect
from django.conf import settings
import json,os
import threading

# Create your views here.

def home(request):
    return render(request, 'home/index.html')

def manage(request):    
    path=settings.BASE_DIR
    spider_json_path=os.path.join(path,'spiders','spider_control.json')
    context={}
    with open(spider_json_path,'r') as f:
        json_data=json.load(f)
        context['spiders']=json_data
    
    return render(request, 'home/manage.html',context=context)

def run_spider(request,id):
    from django.conf import settings
    path=settings.BASE_DIR
    spider_json_path=os.path.join(path,'spiders','spider_control.json')
    with open(spider_json_path,'r') as f:
        json_data=json.load(f)
        for i in range(len(json_data)):
            if json_data[i]['id']==id:
                spider_name=json_data[i]['name']
                threading.Thread(target=lambda:os.system(f'python {path}/spiders/spiders/{spider_name}.py')).start()
                json_data[i]['status']='running'
                break
        with open(spider_json_path,'w') as f:
            f.write(json.dumps(json_data,indent=4,ensure_ascii=False))
        context={"spiders":json_data,}
    return redirect('/manage', context=context)